<template>
	<div id="app" v-loading.fullscreen.lock="loading">
		<el-container class="app-container">
			<el-main>
				<div class="basicInformation">
					<h1>基础信息</h1>
					<el-form :inline="true" class="slForm" ref="slForm" :model="slForm" :rules="rules"
						label-position="right">
						<el-row>
							<el-col :span="8">
								<el-form-item style="width:100%" prop="collectWay">
									<template #label>
										收款方式
										<el-popover placement="right" width="400" trigger="hover">
											<h3>请仔细阅读以下说明</h3>
											<p>如有<span>一次性收款</span>，直接选择“一次性收款并结项”</p>
											<p>如有<span>分三次及三次以上收款</span>，第一次选择“申请首次收款”，第二次选择“申请尾款”</p>
											<p>如有<span>分三次及三次以上收款</span>，第一次选择“申请首次收款”，中间付款选择“申请阶段收款”，最后一笔选择“申请尾款”
											</p>
											<p><span>据实结算</span>的收款方式仅支持费用类型是会议类，框架服务模式，按场次收款的项目，可多次申请
											</p>
											<i class="el-icon-info" slot="reference"></i>
										</el-popover>
									</template>
									<el-select style="width:100%" disabled v-model="slForm.collectWay"
										placeholder="请选择收款方式" @change="getProjectConfigFun">
										<el-option v-for="(item,i) in collectWayEnums" :key="i" :label="item.label"
											:value="item.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item style="width:100%" prop="feeType">
									<template #label>费用类型</template>
									<el-select style="width:100%" v-model="slForm.feeType" placeholder="请选择收款方式"
										disabled>
										<el-option v-for="(item,i) in feeTypeEnums" :key="i" :label="item.label"
											:value="item.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item style="width:100%" prop="projectName">
									<template #label>项目名称</template>
									<el-input style="width:100%" v-model="slForm.projectName" placeholder="请输入项目名称"
										disabled></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item style="width:100%" v-if="slForm.lastDetail">
									<template #label>上阶段收款金额</template>
									<el-input style="width:100%" disabled type="number"
										v-model.number="slForm.lastUsedMoney" placeholder="请完善上阶段结算明细">
										<template slot="append">元</template>
									</el-input>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item style="width:100%" prop="applyMoney">
									<template #label>本次收款金额</template>
									<el-input style="width:100%" disabled type="number"
										v-model.number="slForm.applyMoney" placeholder="请完善结算明细">
										<template slot="append">元</template>
									</el-input>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item style="width:100%" prop="supplierName">
									<template #label>供应商名称</template>
									<el-input style="width:100%" disabled v-model="slForm.supplierName"
										placeholder="请输入供应商名称"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item style="width:100%" prop="feeTypeNo">
									<template #label>金蝶费用类型</template>
									<el-select style="width:100%" disabled v-model="slForm.feeTypeNo" filterable
										placeholder="请选择金蝶费用类型">
										<el-option v-for="item in expenseItem" :key="item.expenseItemID"
											:label="item.expenseItem" :value="item.expenseItemID">
										</el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item style="width:100%">
									<template #label>金蝶项目编号</template>
									<el-input disabled style="width:100%" v-model="slForm.projectNo"
										placeholder="请输入金蝶项目编号"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item style="width:100%" prop="receiptType">
									<template #label>发票类型</template>
									<el-select style="width:100%" disabled v-model="slForm.receiptType"
										placeholder="请选择收款方式">
										<el-option v-for="(item,i) in receiptTypeEnums" :key="i" :label="item.label"
											:value="item.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item style="width:100%" prop="deliveryNum">
									<template #label>快递单号</template>
									<el-input style="width:100%" disabled v-model="slForm.deliveryNum"
										placeholder="邮寄纸质材料快递单号 (若无不填写)"></el-input>
								</el-form-item>
							</el-col>


							<el-col :span="24">
								<el-form-item style="width:100%" prop="meetingIds">
									<template #label>本次结算会议</template>
									<el-select style="width:100%" v-model="slForm.meetingIds" placeholder="请选择您要结算的会议"
										clearable multiple :collapse-tags="false" disabled>
										<el-option v-for="item in meetingList" :key="item.id" :label="item.meetingTitle"
											:value="Number(item.id)">
											{{ item.meetingTitle }} / {{ $moment(item.updateTime).format('lll') }}
										</el-option>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</div>

				<div class="review-container">
					<div class="viewOpts">
						<div class="back backHome">
							<el-button size="mini" plain type="info" icon="el-icon-arrow-left"
                         @click="handleIndexPage">返回首页
							</el-button>
						</div>
						<div class="back">
							<el-button size="mini" plain type="info" icon="el-icon-arrow-left"
                         @click="handleBack">返回
							</el-button>
						</div>
						<div class="meeting-select">
							<span>会议名称选择：</span>
							<el-select size="small" v-model="selectedMeetingId" placeholder="请选择会议"
								@change="handleMeetingChange">
								<el-option v-for="meeting in folderList" :key="meeting.meetingId"
									:label="meeting.meetingName" :value="meeting.meetingId" />
							</el-select>
						</div>
						<div class="detail-select">
							<span>明细选择：</span>
							<el-select size="small" v-model="selectedDetailId" placeholder="请选择明细"
								@change="handleDetailChange">
								<el-option v-for="detail in currentDetails" :key="detail.id"
									:label="`${getProjectLabel(detail.spendingProjectCode)}（金额：${detail.money}元）`"
									:value="detail.id  " />
							</el-select>
						</div>
					</div>

					<!-- 文件夹结构展示 -->
					<div v-if="currentDetail">
						<div class="reviewfileList" v-for="(item,index) in currentDetail.folderNodeList" :key="index">
							<div class="page-title">
								<i class="el-icon-document"></i>{{ item.folderName }}
							</div>
<!--							<div style="margin-bottom: 20px"> {{ item.fileUploadRequirement }}</div>-->

              <UploadRequirementExample
                  :project="item"
              />


							<div class="material-list">
								<div class="material-item">
									<div class="material-header">
										<div class="material-title">{{ item.folderName }}
											<span class="status-badge" :class="{
                        'orange': item.auditStatus === 0 || !item.auditStatus,
                        'red': item.auditStatus === 2
                      }">
												{{
                          item.auditStatus === 0 || !item.auditStatus ? '待审核' : item.auditStatus === 1 ? '审核通过' : item.auditStatus === 2 ? '审核驳回' : '未知状态'
                        }}
											</span>
										</div>
										<div class="material-status">
											<div>
												<el-button v-if="item.auditStatus !== 1" size="mini" type="success"
													@click="apply(item)">
													<i class="el-icon-view"></i> 审核通过
												</el-button>
												<el-button v-if="item.auditStatus !== 2" size="mini" type="warning"
													@click="annotate(item)">
													<i class="el-icon-edit"></i> 整体标注
												</el-button>
											</div>
										</div>
									</div>

									<!-- 整体标注提示 -->
									<span class="" style="color: darkred;"
										v-if="(item.examineMessage || item.aiExamineMessage) && item.auditStatus !== 1">
										【整体标注】{{ item.examineMessage || item.aiExamineMessage }}；
									</span>

									<!-- 每个文件的单独提示 -->
									<div v-for="(log, i) in item.files" :key="i">
										<span class="" style="color: orangered;"
											v-if="(log.examineMessage || log.aiExamineMessage) && item.auditStatus !== 1">
											<!--											【{{ getShortFileName(log.fileName) }}】-->
											{{ log.fileName }}
											:{{ log.examineMessage || log.aiExamineMessage }}；
										</span>
									</div>

									<!-- 文件列表 -->
									<div class="file-list">
										<div v-for="(file,findex) in item.files" :key="findex" class="file-item"
											@mouseenter="hoveredFile = file" @mouseleave="hoveredFile = null">
											<div class="file-preview">
												<img class="file-icon" v-if="isPdf(file.fileName)"
													src="../../../assets/imgs/pdf.png" alt="">
												<img class="file-icon" v-else-if="isImage(file.fileName)"
													:src="file.ossUrl" alt="">
												<img class="file-icon" v-else-if="isWord(file.fileName)"
													src="../../../assets/imgs/doc.png">
												<img class="file-icon" v-else-if="isExcel(file.fileName)"
													src="../../../assets/imgs/xls.png">
												<img class="file-icon" v-else-if="isPPT(file.fileName)"
													src="../../../assets/imgs/ppt.png">
                        <img class="file-icon" v-else-if="isZipFile(file.fileName)"
                             src="../../../assets/imgs/zip.png">
												<i v-else class="icon-other el-icon-document"></i>

												<!-- 审核提示图标 -->
												<div v-if="file.examineMessage || file.aiExamineMessage" class="file-warning-icon">
													<el-tooltip effect="dark" :content="file.examineMessage || file.aiExamineMessage"
														placement="top">
														<i class="el-icon-warning"></i>
													</el-tooltip>
												</div>

												<!-- 悬浮遮罩层 -->
												<div v-if="hoveredFile === file" class="file-hover-mask">
													<div class="mask-buttons">
														<el-button size="mini" @click.stop="previewFile(file,item.files)"
															class="mask-button">
															<i class="el-icon-view"></i> 预览
														</el-button>
														<el-button size="mini" @click.stop="annotateFile(file)"
															class="mask-button">
															<i class="el-icon-edit"></i> 审核
														</el-button>

                            <el-button size="mini" @click.stop="downloadFileFun(file)"
                                       class="mask-button">
                              <i class="el-icon-download"></i> 下载
                            </el-button>

													</div>
												</div>
											</div>
											<div class="file-name">{{ file.fileName }}</div>
										</div>

										<div class="noFile" v-if="!item.files.length">
											<i class="el-icon-folder-delete"></i> 没有文件
										</div>
									</div>









								</div>
							</div>
						</div>
					</div>
				</div>


			</el-main>
		</el-container>

		<!--    <div class="formOptions" v-if="slForm.status=='OFFICIAL_EXAMINE'">-->
		<!--      <el-button type="primary" @click="openAuditDialog('SUCCESS')">审核通过</el-button>-->
		<!--      <el-button type="danger" @click="openAuditDialog('ERROR')">审核退回</el-button>-->
		<!--    </div>-->


		<!--    <div class="auditLog">-->
		<!--      <h1>审核日志</h1>-->
		<!--      <el-table :data="logList" border class="">-->
		<!--        <el-table-column prop="createTime" label="审核时间" align="center">-->
		<!--        </el-table-column>-->
		<!--        <el-table-column prop="operatorName" label="审核人" align="center">-->
		<!--        </el-table-column>-->
		<!--        <el-table-column prop="status" label="审核结果" align="center">-->
		<!--          <template #default="scope">-->
		<!--            {{ formatStatus(scope.row) }}-->
		<!--          </template>-->
		<!--        </el-table-column>-->
		<!--        <el-table-column prop="remark" label="驳回原因" align="center">-->
		<!--          <template #default="scope">-->
		<!--            <div v-if="scope.row.status=='ERROR'">-->
		<!--              {{scope.row.remark}}-->
		<!--            </div>-->

		<!--          </template>-->
		<!--        </el-table-column>-->
		<!--      </el-table>-->
		<!--    </div>-->

		<!-- PDF等文件预览弹窗 -->
		<file-preview ref="childPreview" :visible.sync="showPreview" :url="previewUrl" :options="files" @closeNum="getNum"  />

		<!-- 文件标注弹窗 -->
		<el-dialog custom-class="annotationDialog" :title="'审核文件 - ' + currentFileToAnnotate.fileName"
			:close-on-click-modal="false" :visible.sync="fileAnnotateDialogVisible">


			<!-- 右上角按钮：查看历史审核记录 -->
			<div style="text-align: right; ">
				<el-button type="text" @click="handleViewHistory">
					查看历史审核记录
				</el-button>
			</div>


			<!-- 审核操作选择：通过 or 驳回 -->
			<el-radio-group v-model="annotationStatus" style="margin-bottom: 15px;">
				<el-radio :label="1">初审通过</el-radio>
				<el-radio :label="2">初审驳回</el-radio>
			</el-radio-group>

			<!-- 驳回原因输入框（仅当选择“驳回”时显示） -->
			<el-input type="textarea" :rows="4"
                :placeholder="annotationStatus === 2 ? '请输入文件驳回原因' : '请输入备注（选填）'"
                v-model="fileAnnotationText"
				maxlength="300" show-word-limit></el-input>


			<span slot="footer" class="dialog-footer">
				<el-button @click="fileAnnotateDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="saveFileAnnotation">保存</el-button>
			</span>
		</el-dialog>

		<!-- 标注弹窗 -->
		<el-dialog custom-class="annotationDialog" :title="'审核 - ' + currentAnnotateMaterial.folderName"
			:visible.sync="annotateDialogVisible" width="60%">
			<el-input type="textarea" :rows="4" placeholder="请输入标注内容" v-model="annotationText"></el-input>
			<span slot="footer" class="dialog-footer">
				<el-button @click="annotateDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="saveAnnotation">保存标注</el-button>
			</span>
		</el-dialog>

		<!-- 通用审核弹窗 -->
		<el-dialog custom-class="reviewDialog" :title="this.dialogType === 'SUCCESS' ? '审核通过确认' : '审核退回'"
			:visible.sync="auditDialogVisible" width="500px" append-to-body>
			<div class="form">
				<h2 v-if="dialogType != 'ERROR'">提交事由：</h2>
				<div v-if="dialogType != 'ERROR'" class="tips">提交事由将会在金蝶中的事由字段中做展示</div>
				<el-form :model="auditForm" ref="auditForm" :rules="auditRules">
					<!-- 动态显示不同字段 -->
					<el-form-item v-if="dialogType === 'SUCCESS'" label="审核备注" prop="remark">
						<el-input maxlength="100" show-word-limit type="textarea" :rows="4" placeholder="请输入审核备注"
							v-model="auditForm.remark"></el-input>
					</el-form-item>
					<el-form-item v-if="dialogType === 'ERROR'" label="退回原因" prop="errorMessage">
						<el-input maxlength="100" show-word-limit type="textarea" :rows="4" placeholder="请输入退回原因"
							v-model="auditForm.errorMessage"></el-input>
					</el-form-item>
				</el-form>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="auditDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="confirmAudit">确 定</el-button>
			</span>
		</el-dialog>


		<!-- 弹窗组件 -->
		<HistoryReviewDialog v-if="this.currentFileToAnnotate.id" v-model="showHistoryDialog" :file-id="this.currentFileToAnnotate.id" />

	</div>
</template>

<script>
	import {
		allSpendFolderListOfOfficial,
		annotateFile,
		annotateFolder,
		examineSpendingOrder,
		getOrderByIdWithOfficial,
		getOrderMeetingListByOrderId,
		listOrderLog,
		officialGetExpenseItem,
		queryFile
	} from '@/request/api'
	import FilePreview from '@/components/FilePreview.vue';
	import HistoryReviewDialog from '@/components/HistoryReviewDialog.vue';
  import UploadRequirementExample  from "@/components/UploadRequirementExample/UploadRequirementExample.vue";


	export default {
		name: 'viewDetail',
		components: {
			FilePreview,
			HistoryReviewDialog,
      UploadRequirementExample
		},

		computed: {
			// 获取会议列表（等价于你原来的 folderList）
			folderListData() {
				return this.folderList || [];
			},
			// 当前会议下的明细列表
			currentDetails() {
				if (!this.selectedMeetingId) return [];
				const meeting = this.folderListData.find(m => m.meetingId === this.selectedMeetingId);
				return meeting ? meeting.details : [];
			}
		},
		data() {
			return {
        num:-1,
				showHistoryDialog: false, //展示文件历史审核日志
				selectedMeetingId: null, // 当前选中的会议 ID
				selectedDetailId: null, // 当前选中的明细 ID
				currentDetail: null, // 当前选中的明细对象

				loading: false,
				//审核日志
				logList: [],
				expenseItem: [],
				slForm: {
					collectWay: '', // 收款方式
					feeType: '', // 费用类型
					projectName: '', // 项目名称
					supplierName: '', // 供应商名称
					applyMoney: 0, // 本次收款金额
					receiptType: '', // 发票类型
					deliveryNum: '', // 快递单号
					spendingDetailDtos: [{
						detailType: "",
						id: "",
						spendingProjectCode: "UM000",
						money: ''
					}], //
					feeTypeNo: '',
					projectNo: ''
				},
				feeTypeEnums: [{
						value: "0",
						label: "会议类"
					},
					{
						value: '1',
						label: "非会议类"
					}
				],
				receiptTypeEnums: [{
						value: "0",
						label: "电子发票"
					}, {
						value: "1",
						label: "纸质发票"
					},
					{
						value: "2",
						label: "电子+纸质发票"
					}
				],

				collectWayList: {
					"0": "一次性收款并结项",
					"1": "首次收款",
					"2": "阶段收款",
					"3": "尾款",
					"4": "据实结算",
				},

				collectWayEnums: [{
					value: "0",
					label: "一次性收款并结项"
				}, {
					value: "1",
					label: "首次收款"
				}, {
					value: "2",
					label: "阶段收款"
				}, {
					value: "3",
					label: "尾款"
				}, {
					value: "4",
					label: "据实结算"
				}],
				auditForm: {
					remark: '', // 审核通过备注
					errorMessage: '' // 审核退回原因
				},
				auditDialogVisible: false, // 控制弹窗显示
				dialogType: '', // 操作类型：SUCCESS/ERROR
				// 表单验证规则
				auditRules: {
					remark: [{
							required: true,
							message: '请输入备注',
							trigger: 'blur'
						},
						{
							min: 5,
							message: '备注不能少于5个字符',
							trigger: 'blur'
						}
					],
					errorMessage: [{
							required: true,
							message: '请输入退回原因',
							trigger: 'blur'
						},
						{
							min: 5,
							message: '原因不能少于5个字符',
							trigger: 'blur'
						}
					]
				},
				projectTree: [],
				meetingList: [],
				hoveredFile: null, // 当前悬停的文件
				folderList: [],
				// materials: folderData.children,
				showPreview: false,
				previewUrl: '',
				isPdfPreview: false,
				isImagePreview: false,
				currentFile: null,
        files:[],
				annotationStatus: 2,
				currentFileToAnnotate: {
					fileName: ''
				}, // 要标注的文件
				annotateDialogVisible: false,
				fileAnnotateDialogVisible: false, // 文件标注弹窗
				annotationText: '',
				fileAnnotationText: '', // 文件标注内容
				currentAnnotateMaterial: {
					folderName: ''
				},
				spendId: this.$route.query.id,
				rules: {
					collectWay: [{
						required: true,
						message: '请选择收款方式',
						trigger: 'change'
					}],
					feeType: [{
						required: true,
						message: '请选择费用类型',
						trigger: 'change'
					}],
					projectName: [{
						required: true,
						message: '请输入项目名称',
						trigger: 'change'
					}],
					supplierName: [{
						required: true,
						message: '请输入供应商名称',
						trigger: 'change'
					}],
					applyMoney: [{
						required: true,
						message: '请完善本次收款明细',
						trigger: 'change'
					}],
					lastUsedMoney: [{
						required: true,
						message: '请完善上阶段支出明细',
						trigger: 'change'
					}],
					receiptType: [{
						required: true,
						message: '请选择发票类型',
						trigger: 'change'
					}],
					deliveryNum: [{
						required: false,
						message: '请输入快递单号',
						trigger: 'blur'
					}],
					meetingIds: [{
						required: true,
						message: '请选择您要结算的会议场次',
						trigger: 'change'
					}],
					projectNo: [{
						required: true,
						message: '请输入金蝶项目编号',
						trigger: 'change'
					}],
					feeTypeNo: [{
						required: true,
						message: '请选择金蝶项目类型',
						trigger: 'change'
					}]
				},
			}
		},
		mounted() {
			this.orderId = this.$route.query.orderId
			this.selectedMeetingId = Number(this.$route.query.selectedMeetingId) // 当前选中的会议 ID
			this.selectedDetailId = this.$route.query.selectedDetailId.toString() // 当前选中的明细 ID


			this.getParams();
			this.getExpenseItemFun();
			this.loadData();
			this.loadLog();
		},
		methods: {
      handleIndexPage(){
        sessionStorage.setItem("pageNum",-1);
        this.$router.push(`/fileListPreviewnew?orderId=${this.$route.query.orderId}`)
      },
      handleBack(){
        this.num=sessionStorage.getItem("pageNum");
        if(this.num!= -1){
          this.$router.go(this.num)
          sessionStorage.setItem("pageNum",-1);
          return;
        }
        this.$router.go(-1)
      },

      getNum(num){
        console.log("得到"+num)
        this.num=num
      },
			handleViewHistory() {
				this.showHistoryDialog = true
			},

			// 获取项目名称
			getProjectLabel(code) {
				const project = this.projectTree.find(p => p.id == code);
				return project ? project.projectType : '未知项目';
			},

			// 会议选择变化
			handleMeetingChange() {
				this.selectedDetailId = null;
				this.currentDetail = null;
			},

			// 明细选择变化
			handleDetailChange() {
				if (!this.selectedDetailId) return;
				this.currentDetail = this.currentDetails.find(d => d.id === this.selectedDetailId);
			},

			//查询审核日志
			loadLog() {
				listOrderLog({
					orderId: this.$route.query.orderId
				}).then(res => {
					if (res.code == 200) {
						this.logList = res.data;
					}
				})
			},
			formatStatus(item) {
				const status = item.status
				const statusMap = {
					OFFICIAL_EXAMINE: '待审核',
					SUBMIT: '初审通过',
					ERROR: '初审驳回',
					SUCCESS: '初审通过'
				};
				if (item.operatorId == '0' && status == 'ERROR') {
					return "复审驳回"
				}
				return statusMap[status] || '未知状态';
			},
			// 确认审核操作
			confirmAudit() {
				this.$refs.auditForm.validate(valid => {
					if (valid) {
						this.examineSpendingOrder();
						this.auditDialogVisible = false;
					}
				});
			},
			examineSpendingOrder() {
				console.log('备注：', this.auditForm.remark);
				console.log('审核退回，原因：', this.auditForm.errorMessage);
				this.loadingText = '正在提交···'
				this.loading = true;
				examineSpendingOrder({
					orderId: this.slForm.id,
					status: this.dialogType,
					remark: this.auditForm.remark,
					errorMessage: this.auditForm.errorMessage
				}).then(res => {
					this.loading = false;
					if (res.code == 200) {
						this.$message({
							message: '操作成功',
							type: 'success'
						});
						this.getSheetDataFun();
						this.loadLog()
					} else {
						this.$message({
							message: res.msg,
							type: 'error'
						});
					}
				})
			},
			getExpenseItemFun(itemName) {
				let data = {}
				data.current = 1;
				data.size = 3000;
				if (itemName) data.itemName = itemName
				officialGetExpenseItem(data).then(res => {
					if (res.code == 200) {
						this.expenseItem = res.data.data
					}
				})
			},
			getParams() {
				this.getSheetDataFun();
				this.getProjectConfigFun();
				// 获取当前用户token
				// this.token = localStorage.getItem('regToken') ? JSON.parse(localStorage.getItem('regToken')).token : JSON
				//     .parse(localStorage.getItem('token')).token;
			},
			// 获取结算单信息
			getSheetDataFun() {
				getOrderByIdWithOfficial({
					orderId: this.$route.query.orderId
				}).then(res => {
					if (res.code == 200) {
						let resData = JSON.parse(JSON.stringify(res.data));
						for (let i in resData) {
							if (resData[i] == null) resData[i] = '';
						};
						if (resData.collectWay == 2 || resData.collectWay == 3) {
							resData.lastDetail = [];
							// resData.lastUsedMoney = '';
							let array = []
							resData.spendingDetailDtos.map((item, i) => {
								if (item.detailType == "L") {
									resData.lastDetail.push(item);
								} else {
									array.push(item);
								}
							});
							resData.spendingDetailDtos = array;
						}
						if (resData.meetingIds) {
							// resData.meetingIds
							console.log(resData.meetingIds);
						} else {
							resData.meetingIds = [];
						};
						// console.log(resData);
						this.slForm = resData;
						this.meetingList = resData.meetingList || [];


            // this.$forceUpdate()
						this.getMeetingList();
					};
				});
			},
			// 获取会议列表
			getMeetingList() {

				// orderMeetingListBOfficial(data).then(res => {
				//   if (res.code == 200) this.meetingList = res.data;
				// });
				getOrderMeetingListByOrderId({
          orderId: this.orderId
        }).then(res => {
					if (res.code == 200) {
            this.meetingList = res.data;
          }
				});
			},
			// 获取支出明细类型列表
			getProjectConfigFun() {
				allSpendFolderListOfOfficial().then(res => {
					if (res.code == 200) {
						this.projectTree = res.data
					}
				})
			},
			loadData() {
				queryFile({
					id: this.$route.query.orderId
				}).then((res) => {
					console.log(res)
					if (res.code == 200) {
						this.folderList = res.data;
						// 关键点：重新加载当前选中的明细，触发视图刷新
						this.handleDetailChange();

					}
				})
			},
			// 打开审核弹窗
			openAuditDialog(type) {
				this.dialogType = type;
				this.auditDialogVisible = true;
				this.resetForm();
				if (type === 'SUCCESS') {
					this.auditForm.remark =
						`【会议合规管理】-供应商结算-${this.slForm.projectName}-${this.collectWayList[this.slForm.collectWay]}`;
				}
			},
			// 重置表单
			resetForm() {
				this.auditForm = {
					remark: '',
					errorMessage: ''
				};
				if (this.$refs.auditForm) {
					this.$refs.auditForm.resetFields();
				}
			},
			// 打开文件标注对话框
			annotateFile(file) {
				this.currentFileToAnnotate = file;
				this.fileAnnotationText = file.examineMessage || '';
				this.fileAnnotateDialogVisible = true;
			},

      // 下载文件
      downloadFileFun(row) {
        console.log(row)
        if (this.isZipFile(row.fileName)) {
          // if (row.type == "FOLDER") {
          this.loadingText = '正在下载文件夹';
          this.loading = true;
          this.download('/signLive/order/downloadFolderById', {
            folderId: row.id
          }, row.folderName`_${new Date().getTime()}.zip`)
        } else {
          this.loadingText = '正在下载文件';
          this.loading = true;

          setTimeout(() => {
            this.loading = false;
            const x = new XMLHttpRequest();
            x.open("GET", row.ossUrl, true);
            x.responseType = 'blob';
            x.onload = function(e) {
              const url = window.URL.createObjectURL(x.response);
              const a = document.createElement('a');
              a.href = url;
              a.target = '_blank';
              a.download = row.fileName;
              a.click();
              a.remove();
            };
            x.send();
          }, 1000);
        };
      },

      // 判断是否是压缩文件
      isZipFile(filename) {
        const ext = filename.toLowerCase().split('.').pop();
        return ['zip', 'rar', 'tar', 'gz', '7z'].includes(ext);
      },

      // 判断文件是否为PDF
			isPdf(fileName) {
				return fileName.toLowerCase().endsWith('.pdf');
			},
			// 判断文件是否为图片
			isImage(fileName) {
				const imgExts = ['.jpg', '.jpeg', '.png', '.gif', '.bmp'];
				return imgExts.some(ext => fileName.toLowerCase().endsWith(ext));
			},
			isWord(filename) {
				return /\.(doc|docx)$/i.test(filename);
			},
			isExcel(filename) {
				return /\.(xls|xlsx)$/i.test(filename);
			},
			isPPT(filename) {
				return /\.(ppt|pptx)$/i.test(filename);
			},
			// 获取短文件名（防止文件名过长）
			getShortFileName(fileName) {
				if (fileName.length > 15) {
					return fileName.substring(0, 8) + '...' + fileName.slice(-7);
				}
				return fileName;
			},
			// 预览单个文件
			previewFile(file,files) {
				console.log(file)

        this.files = files.map(file => ({
          url: file.ossUrl,
          fileName: file.fileName
        }));
				this.currentFile = file;
				this.previewUrl = file.ossUrl;
				this.showPreview = true;
        this.$refs.childPreview.openModal()
			},
			// 预览整个文件夹
			previewFiles(material) {
				if (material.files.length > 0) {
					this.previewFile(material.files[0]);
				} else {
					this.$message.warning('此材料项下暂无文件可预览');
				}
			},
			// 关闭预览
			closePreview() {
				this.showPreview = false;
				this.previewUrl = '';
			},
			// 下载文件
			downloadFile() {
				if (this.currentFile) {
					window.open(this.currentFile.ossUrl, '_blank');
				}
			},
			// 打开标注对话框
			annotate(material) {
				this.currentAnnotateMaterial = material;
				this.annotationText = ''; // 清空之前的标注
				this.annotationStatus = 2
				this.annotateDialogVisible = true;
			},
			//文件夹审核通过
			apply(material) {
				//文件夹整体审核通过
				annotateFolder({
					folderId: material.id,
					auditStatus: 1 //1审核通过 2审核驳回
				}).then(res => {
					console.log(res)
					if (res.code == 200) {
						this.$message.success('标注已保存');
						this.loadData()
					}
				})
			},
			// 保存标注
			saveAnnotation() {
				if (!this.annotationText.trim()) {
					this.$message.warning('请先输入标注内容');
					return;
				}
				annotateFolder({
					folderId: this.currentAnnotateMaterial.id,
					annotation: this.annotationText,
					auditStatus: 2 //1审核通过 2审核驳回
				}).then(res => {
					console.log(res)
					if (res.code == 200) {
						this.$message.success('标注已保存');
						this.annotateDialogVisible = false;
						this.loadData()
					}
				})
			},
			// 保存文件标注
			saveFileAnnotation() {


        // 只有在“驳回”时才需要校验必须填写原因
        if (this.annotationStatus == 2) { // 假设 2 表示“驳回”
          if (!this.fileAnnotationText.trim()) {
            this.$message.warning('请填写文件驳回原因');
            return;
          }
        }

				annotateFile({
					orderId: this.orderId,
					fileId: this.currentFileToAnnotate.id,
					annotation: this.fileAnnotationText,
					auditStatus: this.annotationStatus //1审核通过 2审核驳回
				}).then(res => {
					console.log(res)
					if (res.code == 200) {
						this.$message.success('文件标注已保存');
						this.fileAnnotateDialogVisible = false;
						this.loadData()
					}else {
            this.$message.error(res.msg)
          }
				})
			},
			// 模拟上传文件
			uploadFile(material) {
				this.$message.info('文件上传功能已触发，实际项目中调用上传API');
			},
			// 显示详情
			showMaterialDetails(material) {
				this.$message({
					message: `${material.folderName} 的详细信息`,
					customClass: 'custom-message',
					duration: 2000,
					iconClass: 'el-icon-info'
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	body {
		margin: 0;
		padding: 0;
		font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
		background-color: #f5f7fa;
	}

	.app-container {
		//max-width: 1200px;
		margin: 20px auto;
		padding: 0 20px;
	}


	.material-list {
		background-color: #fff;
		border-radius: 4px;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
		overflow: hidden;
	}

	.material-item {
		border-bottom: 1px solid #eaeef5;
		padding: 20px;
		transition: background-color .3s;
	}

	.material-item:last-child {
		border-bottom: none;
	}

	.material-item:hover {
		background-color: #f9fbfd;
	}

	.material-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 15px;
	}

	.material-title {
		font-weight: 500;
		font-size: 16px;
		color: #1f2d3d;
	}

	.material-status {
		display: flex;
		align-items: center;
		gap: 15px;
	}

	.status-badge {
		padding: 4px 10px;
		font-size: 12px;
		border-radius: 12px;
		background-color: #ecf5ff;
		color: #67c23a;
		border: 1px solid #e1f3d8;
	}

	.status-badge.orange {
		background-color: #fdf6ec;
		color: #e6a23c;
		border-color: #faecd8;
	}

	.status-badge.red {
		background-color: #fdf6ec;
		color: red;
		border-color: #faecd8;
	}

	.file-list {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
		gap: 15px;
		margin-top: 15px;
	}

	.file-item {
		position: relative;
		width: 100px;
		//height: 100px;
		//border: 1px dashed #dcdfe6;
		//border-radius: 4px;
		display: flex;
		flex-direction: column;
		align-items: center;
		//justify-content: center;
		cursor: pointer;
		transition: border-color .3s;

		.file-preview {
			position: relative;
			background-color: #fff;
			width: 100%;
			width: 100%;
			//height: 60px;
			display: flex;
			justify-content: center;
			align-items: center;
			box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
			border-radius: 10px;
			overflow: hidden;

			.file-icon {
				width: 100px;
				height: 100px;
				object-fit: contain;
				/* 可选：保持图片比例 */
			}
		}
	}

	.file-item:hover {
		border-color: #409eff;
	}

	//.file-preview {
	//  width: 60px;
	//  height: 60px;
	//  display: flex;
	//  align-items: center;
	//  justify-content: center;
	//  font-size: 40px;
	//  color: #909399;
	//}


	/* 文件右上角提示符号 */
	.file-warning-icon {
		position: absolute;
		top: 4px;
		right: 4px;
		// width: 20px;
		// height: 20px;
		// background: #E6A23C;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		color: white;
		cursor: pointer;
		z-index: 2;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);

		i {
			font-size: 17px;
			font-weight: bold;
			color: #E6A23C;
		}
	}

	/* 文件悬浮遮罩层 */
	.file-hover-mask {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.6);
		border-radius: 4px;
		display: flex;
		justify-content: center;
		align-items: center;
		transition: all 0.3s ease;
		z-index: 1;

		.mask-buttons {
			display: flex;
			flex-direction: column;
			align-items: center;
			width: 100%;
		}

		.mask-button {
			margin: 4px 0;
			width: 80px;
			background: rgba(255, 255, 255, 0.8);
			border: none;

			&:hover {
				background: white;
			}
		}
	}

	.file-name {
		margin-top: 8px;
		text-align: center;
		font-size: 12px;
		color: #606266;
		width: 100%;
		overflow: hidden;
		text-align: justify;
		word-break: break-all;
		text-overflow: ellipsis;
		//-webkit-line-clamp: 3;
		display: -webkit-box;
		-webkit-box-orient: vertical;
	}

	.action-panel {
		display: flex;
		gap: 8px;
		justify-content: flex-end;
		margin-top: 10px;
	}

	.upload-placeholder {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: #909399;
		height: 100%;
	}

	.upload-placeholder i {
		font-size: 28px;
		margin-bottom: 5px;
	}

	.icon-pdf {
		color: #f56c6c;
	}

	.icon-image {
		color: #67c23a;
	}

	.icon-other {
		color: #909399;
	}

	.pdf-viewer-container {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, .8);
		z-index: 9999;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.pdf-viewer {
		width: 80%;
		height: 90%;
	}

	.close-preview {
		position: absolute;
		top: 20px;
		right: 20px;
		font-size: 24px;
		color: white;
		cursor: pointer;
	}

	.formOptions {
		margin: 20px;
		display: flex;
		justify-content: center;
	}

	.noFile {
		width: 100px;
		height: 80px;
		//margin: 0 20px;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		box-shadow: 0 2px 18px rgba(190, 190, 190, 0.31);
		border-radius: 10px;
		padding: 10px;
		color: #ccc;
		font-size: 16px;
		margin-bottom: 10px;

		i {
			font-size: 30px;
		}
	}

	.auditLog {
		margin: 40px;
		padding: 40px;
		box-shadow: 0 2px 18px rgba(190, 190, 190, 0.31);
		border-radius: 4px;

		h1 {
			margin-bottom: 20px;
			font-size: 20px;
		}
	}

	.basicInformation {
		padding: 40px;
		box-shadow: 0 2px 18px rgba(190, 190, 190, 0.31);
		border-radius: 4px;

		h1 {
			margin-bottom: 20px;
			font-size: 20px;
		}
	}

	::v-deep .slForm {

		.el-form-item {
			display: flex;
			flex-direction: row;

			.el-form-item__label {
				width: 120px;
				text-align: right;
			}

			.el-form-item__content {
				margin-left: 0 !important;
				flex: 1;
			}

		}
	}

	.reviewfileList {
		box-shadow: 0 2px 18px rgba(190, 190, 190, 0.31);
		padding: 40px;
		margin-bottom: 40px;

		.page-title {
			margin: 0 0 20px;
			color: #1f2d3d;
			font-weight: 500;
			font-size: 22px;
			//border-bottom: 1px solid #e6ebf5;
			display: flex;
			align-items: center;
		}

		.page-title i {
			margin-right: 10px;
			font-size: 24px;
			color: #409EFF;
		}

	}

	.review-container {
		.viewOpts {
			display: flex;
			padding: 10px 0;
			align-items: center;

			.meeting-select,
			.detail-select {
				display: flex;
				align-items: center;
				margin-right: 20px;

				p {
					width: auto;
				}
			}

			.back {
				margin-right: 20px;
			}
		}
	}
</style>